package com.logistics.flow.service;

import com.logistics.erp.entity.domain.ErpDeliveryOrderDetail;
import com.logistics.erp.entity.domain.ErpDept;
import com.logistics.erp.entity.model.ErpDirectSave;
import com.logistics.erp.entity.model.ErpStashSave;
import com.logistics.erp.entity.model.MaterialBillRow;
import com.logistics.erp.entity.model.ErpTakeOverSave;
import com.logistics.erp.entity.model.MaterialFlowRow;
import com.logistics.erp.service.ErpOrderService;
import com.logistics.utils.bean.UserBean;
import com.logistics.utils.constants.Constants;
import com.logistics.utils.exception.MessageException;
import com.logistics.utils.tool.StringUtils;
import com.logistics.utils.tool.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FlowService {

    @Autowired
    private ErpOrderService erpOrderService;

    @Autowired
    private UserUtils userUtils;

    private static final String MODE_DIRECT_PUT_AND_STASH = "direct_put_and_stash";
    private static final String MODE_TAKE_OVER = "take_over";

    /**
     * 查询物料信息
     *
     * @param taskNo 任务单号
     * @return
     */
    public MaterialFlowRow materialFlow(String taskNo) throws MessageException {
        UserBean userBean = userUtils.getUserInfo();
        if (!taskNo.startsWith(Constants.TASK_NO_PREFIX)) {
            throw new MessageException("任务单号不符合规则");
        }

        // 根据任务号查找来源为工序交接和内部交接
        List<ErpDeliveryOrderDetail> takeOverList = erpOrderService.findSourceFromTakeOver(taskNo);
        // 判断是否是报工周转
        if (!takeOverList.isEmpty()) {
            // 报工周转
            return takeOver(taskNo);
        }

        // 直流和暂存的查询
        MaterialFlowRow result = erpOrderService.materialFlow(userBean.getErpDeptCode(), taskNo);
        if (StringUtils.isNull(result)) {
            throw new MessageException("该单据不存在");
        }
        List<String> deptCodes = erpOrderService.depByItemCode(result.getItemCode()).stream().
                map(ErpDept::getDeptCode).collect(Collectors.toList());
        if (StringUtils.isEquals(result.getOrderStatus(), "E")  &&
                (StringUtils.isNull(result.getReqQty()) || new BigDecimal(result.getReqQty()).compareTo(BigDecimal.ZERO) <= 0)) {
//            if (!deptCodes.contains(userBean.getErpDeptCode())) {
//                result.setMessage("登录人员所在部门与直流接收部门不一致");
//            }
            if (!deptCodes.isEmpty()){
                List<MaterialBillRow> billRows = erpOrderService.repQtyByDept(deptCodes,taskNo)
                        .stream().filter(item ->
                                item.getReqQty() != null && item.getReqQty().compareTo(BigDecimal.ZERO) > 0
                        ).collect(Collectors.toList());
                if (!billRows.isEmpty()) {
                    // 使用 map 和 joining 来简化字符串拼接
                    String erroMessage = billRows.stream()
                            .map(billRow -> "部门：" + billRow.getDeptCode() + ",需求数量：" + billRow.getReqQty())
                            .collect(Collectors.joining("; ")); // 用 "; " 作为分隔符

                    throw new MessageException("当前部门无需求, 请参考其他部门需求: " + erroMessage);
                }
            }
            // 无需求的情况，提供缓存的功能
            return result;
        }
        if (!StringUtils.isEquals(result.getOrderStatus(), "C") && !deptCodes.contains(userBean.getErpDeptCode())) {
            result.setMessage("登录人员所在部门与直流接收部门不一致");
        } else if (StringUtils.isNotNull(result.getReqQty()) && StringUtils.isNotNull(result.getReceiveQty())
                && Integer.parseInt(result.getReqQty()) != 0
                && Integer.parseInt(result.getReceiveQty()) > Integer.parseInt(result.getReqQty())) {
            result.setMessage("直流量大于领料单需求量，不允许直流，请生成料单后再做业务");
//        }
//        else if (StringUtils.isEquals(result.getOrderStatus(), Constants.ERP_ORDER_STATUS_CLOSE)) {
//            result.setMessage("此任务的数据已经存在，不能重复扫描，请到ERP中处理");
//        } else if (StringUtils.isEquals(result.getIsnbjj(), Constants.ERP_ORDER_IS_NBJJ)) {
//            result.setMessage("内部交接件，不需直流");
        }else if(StringUtils.isEquals(result.getOrderStatus(), Constants.ERP_ORDER_STATUS_CLOSE)){
            result.setMessage("此任务已关闭！去向：【" +result.getIntoDeptW() + "】人员：【"+result.getIntoDeptWName()+"】" + "时间：【" + result.getIntoTime()+"】");
        } else if (!StringUtils.isEquals(result.getOrderStatus(), Constants.ERP_ORDER_STATUS_CLOSE)
                && !StringUtils.isEquals(result.getOrderStatus(), Constants.ERP_ORDER_STATUS_END)) {
            result.setMessage("任务未完工");
        }
        result.setReqQty(StringUtils.isNotNull(result.getReqQty()) ? result.getReqQty() : "0");
        result.setMode(MODE_DIRECT_PUT_AND_STASH);
        return result;
    }

    /**
     * 报工周转逻辑
     *
     * @param taskNo 任务单号
     * @return
     */
    public MaterialFlowRow takeOver(String taskNo) throws MessageException{
        // 判断是否进行过工序交接
        Integer count = erpOrderService.countTakeOver(taskNo);
        String message = "";
        if (count > 0) {
            // 画面提示message
            message = "该任务工序已经交接过！";
        }
        // 获取打印流向标签数据
        List<ErpDeliveryOrderDetail> flowInfo = erpOrderService.findFlowInfoFromProcessAndInside(taskNo);
        if(StringUtils.isNull(flowInfo) || flowInfo.isEmpty()){
            throw new MessageException("没有要打印的标签数据");
        }
        return MaterialFlowRow.build(flowInfo.get(0), message, MODE_TAKE_OVER);
    }

    /**
     * 直投
     *
     * @param erpDirectPut 直投信息
     * @return
     */
    public void save(ErpDirectSave erpDirectPut) throws MessageException {
        UserBean userBean = userUtils.getUserInfo();
        erpDirectPut.setUserUniqueId(userBean.getErpUniqueId());
        erpDirectPut.setReceiveDeptCode(userBean.getErpDeptCode());
        // 查询人员id
        erpOrderService.directPut(erpDirectPut);
        if ("Y".equals(erpDirectPut.getPoReturnFlag()) || "S".equals(erpDirectPut.getPoReturnFlag())) {
            throw new MessageException("直流直送业务记帐失败,请到ERP中进行直流直送业务");
        } else if ("T".equals(erpDirectPut.getPoReturnFlag())) {
            throw new MessageException("此物料非直流直送件,请办理入库");
        }
    }

    /**
     * 暂存
     *
     * @param erpStashSave 暂存信息
     * @return
     */
    public void insertStash(ErpStashSave erpStashSave) {
        // 查找暂存数据
        Integer count = erpOrderService.findNoDemand104T(erpStashSave.getOrderNo(), erpStashSave.getQty());
        if(count > 0){
            // 修改暂存数据
            erpOrderService.updateNoDemand104T(erpStashSave);
        }else{
            // 添加暂存数据
            erpOrderService.insertStash(erpStashSave);
        }
    }

    /**
     * 报工周转
     *
     * @param erpTakeOverSave 报工周转信息
     * @return
     */
    public void insertTakeOver(ErpTakeOverSave erpTakeOverSave) {
        if (Constants.ERP_SOURCE_METHOD_PROCESS_REPORT_TRANSFER.equals(erpTakeOverSave.getSourceMethod()) ||
        Constants.ERP_SOURCE_METHOD_OUT_RETURN.equals(erpTakeOverSave.getSourceMethod())) {
            // 执行工序交接
            erpOrderService.insertPacRoutingOpProcess(erpTakeOverSave.getTaskNo());
        } else if (Constants.ERP_SOURCE_METHOD_INSIDE_TRANSFER.equals(erpTakeOverSave.getSourceMethod())) {
            // 执行内部交接
            erpOrderService.insertPacRoutingOpInside(erpTakeOverSave.getTaskNo());
        }
    }
}
